package com.spzx.common.rabbit.config;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RabbitInitConfigApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.setupCallbacks();
    }

    private void setupCallbacks() {

        /**
         * 只确认消息是否正确到达 Exchange 中,成功与否都会回调
         *
         * @param correlation 相关数据  非消息本身业务数据
         * @param ack             应答结果
         * @param reason           如果发送消息到交换器失败，错误原因
         */
        this.rabbitTemplate.setConfirmCallback((correlationData, ack, reason) -> {
            GuiguCorrelationData guiguCorrelationData = (GuiguCorrelationData) correlationData;
            System.out.println(correlationData);
            if (ack) {
                //消息到交换器成功
                log.info("消息发送到Exchange成功：{}", guiguCorrelationData);
            } else {
                //消息到交换器失败
                log.error("消息发送到Exchange失败：{}", reason);
                log.error("重发消息", guiguCorrelationData);
                retrySend(guiguCorrelationData);
            }
        });

        /**
         * 消息没有正确到达队列时触发回调，如果正确到达队列不执行
         */
        this.rabbitTemplate.setReturnsCallback(returned -> {
            Message message = returned.getMessage();
            byte[] body = message.getBody();
            String msg = new String(body);
            System.out.println(msg);
            String CORRELATIONDATA_ID = (String)message.getMessageProperties().getHeader("spring_returned_message_correlation");
            log.info("投递回调,消息的原始id："+CORRELATIONDATA_ID);// 投递失败才执行
            GuiguCorrelationData guiguCorrelationData = JSON.parseObject((String)redisTemplate.opsForValue().get(CORRELATIONDATA_ID),GuiguCorrelationData.class);
            if(!guiguCorrelationData.isDelay()){
                retrySend(guiguCorrelationData);// 非延迟消息才重试
            }
        });
    }

    private void retrySend(GuiguCorrelationData guiguCorrelationData) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        guiguCorrelationData.setRetryCount(guiguCorrelationData.getRetryCount() + 1);
        if (guiguCorrelationData.getRetryCount() <= 3) {
            redisTemplate.opsForValue().set(guiguCorrelationData.getId(), JSON.toJSONString(guiguCorrelationData), 10, TimeUnit.MINUTES);
            rabbitTemplate.convertAndSend(guiguCorrelationData.getExchange(), guiguCorrelationData.getRoutingKey(), guiguCorrelationData.getMessage(), guiguCorrelationData);
        } else {
            System.out.println("重发次数耗尽，gg");
        }
    }

}
